package com.ideal.frame.institutions.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ideal.frame.entity.AutoModel;
import com.ideal.frame.institutions.dto.InstitutionsLicencelistDto;
import com.ideal.frame.institutions.entity.InstitutionsLicencelistTb;
import com.ideal.frame.institutions.entity.QInstitutionsLicencelistTb;
import com.ideal.frame.jpa.DSLRequest;
import com.ideal.frame.jpa.JpaRepositoryImpl;
import com.ideal.frame.util.UserUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class InstitutionsLicencelistService {
    @PersistenceContext
    protected EntityManager entityManager;
    private JpaRepositoryImpl<InstitutionsLicencelistTb, String> jpaRepository;

    QInstitutionsLicencelistTb qInstitutionsLicencelistTb = QInstitutionsLicencelistTb.institutionsLicencelistTb;


    @PostConstruct
    public void initRepo() {
        jpaRepository = new JpaRepositoryImpl<>(InstitutionsLicencelistTb.class, entityManager);
    }

    @Transactional(rollbackFor = Exception.class)
    public void save1(InstitutionsLicencelistDto institutionsLicencelistDto) {
        Assert.isTrue(institutionsLicencelistDto != null, "参数不能为空");
        String id = institutionsLicencelistDto.getGnrlid();
        Assert.isTrue(StrUtil.isNotBlank(id), "机构id不能为空");
        DSLRequest request = new DSLRequest();
        request.addWhere(qInstitutionsLicencelistTb.gnrlid.eq(id));
        request.addWhere(qInstitutionsLicencelistTb.delFlag.isFalse());
        List<InstitutionsLicencelistTb> all = jpaRepository.findAll(request);
        InstitutionsLicencelistTb institutionsLicencelistTb = new InstitutionsLicencelistTb();
        BeanUtil.copyProperties(institutionsLicencelistDto, institutionsLicencelistTb);
        if (institutionsLicencelistDto.getId() != null) {
            if (CollUtil.isNotEmpty(all)) {
                long count = all.stream().filter(v -> ObjectUtil.equal(v.getGnrlid(), institutionsLicencelistDto.getGnrlid())).count();
                Assert.isTrue(count > 0, "机构id重复，请重新填写！");
            }
            institutionsLicencelistTb.setModifyTime(new Date());
            institutionsLicencelistTb.setModifyUser(UserUtils.getCurrentUser().getId());
        } else {
            Assert.isTrue(CollUtil.isEmpty(all), "机构id重复，请重新填写！");
            institutionsLicencelistTb.setCreateTime(new Date());
            institutionsLicencelistTb.setCreateUser(UserUtils.getCurrentUser().getId());
            institutionsLicencelistTb.setDelFlag(false);
        }
        jpaRepository.save(institutionsLicencelistTb);
    }

    @Transactional(rollbackFor = Exception.class)
    public void save(List<InstitutionsLicencelistDto> institutionsLicencelistDtos, String gnrlid) {
        if (CollUtil.isEmpty(institutionsLicencelistDtos)) {
            return;
        }
        DSLRequest request = new DSLRequest();
        request.addWhere(qInstitutionsLicencelistTb.gnrlid.eq(gnrlid));
        request.addWhere(qInstitutionsLicencelistTb.delFlag.isFalse());
        List<InstitutionsLicencelistTb> all = jpaRepository.findAll(request);
        Assert.isTrue(CollUtil.isEmpty(all), "机构id重复，请重新填写！");
        List<InstitutionsLicencelistTb> collect = institutionsLicencelistDtos.stream().map(v -> {
            InstitutionsLicencelistTb institutionsLicencelistTb = new InstitutionsLicencelistTb();
            BeanUtil.copyProperties(v, institutionsLicencelistTb);
            institutionsLicencelistTb.setGnrlid(gnrlid);
            institutionsLicencelistTb.setCreateTime(new Date());
            institutionsLicencelistTb.setCreateUser(UserUtils.getCurrentUser().getId());
            institutionsLicencelistTb.setDelFlag(false);
            return institutionsLicencelistTb;
        }).collect(Collectors.toList());
        jpaRepository.saveAll(collect);
    }

    @Transactional(rollbackFor = Exception.class)
    public void edit(List<InstitutionsLicencelistDto> institutionsLicencelistDtos, String gnrlid) {
        if (CollUtil.isEmpty(institutionsLicencelistDtos)) {
            deleteById(gnrlid);
        } else {
            DSLRequest request = new DSLRequest();
            request.addWhere(qInstitutionsLicencelistTb.gnrlid.eq(gnrlid));
            request.addWhere(qInstitutionsLicencelistTb.delFlag.isFalse());
            List<InstitutionsLicencelistTb> all = jpaRepository.findAll(request);
            List<Long> deletes = all.stream().map(AutoModel::getId).filter(v -> institutionsLicencelistDtos.stream()
                    .map(InstitutionsLicencelistDto::getId).noneMatch(s -> s.equals(v))).collect(Collectors.toList());
            List<InstitutionsLicencelistTb> collect = institutionsLicencelistDtos.stream().map(v -> {
                InstitutionsLicencelistTb institutionsLicencelistTb = new InstitutionsLicencelistTb();
                BeanUtil.copyProperties(v, institutionsLicencelistTb);
                institutionsLicencelistTb.setGnrlid(gnrlid);
                Long id = v.getId();
                if (id != null) {
                    institutionsLicencelistTb.setModifyTime(new Date());
                    institutionsLicencelistTb.setModifyUser(UserUtils.getCurrentUser().getId());
                } else {
                    institutionsLicencelistTb.setCreateTime(new Date());
                    institutionsLicencelistTb.setCreateUser(UserUtils.getCurrentUser().getId());
                    institutionsLicencelistTb.setDelFlag(false);
                }
                return institutionsLicencelistTb;
            }).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(deletes)) {
                jpaRepository.update(qInstitutionsLicencelistTb).set(qInstitutionsLicencelistTb.delFlag, true)
                        .where(qInstitutionsLicencelistTb.id.in(deletes)).execute();
            }
            jpaRepository.saveAll(collect);
        }
    }

    public InstitutionsLicencelistDto getByGnrlid1(String gnrlid) {
        Optional<InstitutionsLicencelistTb> tb = jpaRepository.findOne(qInstitutionsLicencelistTb.gnrlid.eq(gnrlid)
                .and(qInstitutionsLicencelistTb.delFlag.isFalse()));
        InstitutionsLicencelistDto licencelistDto = new InstitutionsLicencelistDto();
        tb.ifPresent(v -> BeanUtil.copyProperties(v, licencelistDto));
        return licencelistDto;
    }

    public List<InstitutionsLicencelistDto> getByGnrlid(String gnrlid) {
        List<InstitutionsLicencelistTb> all = jpaRepository.findAll(qInstitutionsLicencelistTb.gnrlid.eq(gnrlid)
                .and(qInstitutionsLicencelistTb.delFlag.isFalse()));
        if (CollUtil.isNotEmpty(all)) {
            return all.stream().map(v -> {
                InstitutionsLicencelistDto i = new InstitutionsLicencelistDto();
                BeanUtil.copyProperties(v, i);
                return i;
            }).collect(Collectors.toList());
        } else {
            return new ArrayList<>();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteById(String gnrlid) {
        jpaRepository.update(qInstitutionsLicencelistTb).set(qInstitutionsLicencelistTb.delFlag, true)
                .where(qInstitutionsLicencelistTb.gnrlid.eq(gnrlid)).execute();
    }
}
